package com.yuantu.judiciary.serviceimpl;

import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.yuantu.judiciary.dao.IExternalRequestRecordDao;
import com.yuantu.judiciary.dao.IQueryRecordDao;
import com.yuantu.judiciary.dao.ISearchRecordInfoDao;
import com.yuantu.judiciary.model.api.*;
import com.yuantu.judiciary.model.domain.ExternalQuestRecordDO;
import com.yuantu.judiciary.model.domain.QueryEntityDO;
import com.yuantu.judiciary.model.domain.QueryRecordDO;
import com.yuantu.judiciary.model.domain.SearchRecordInfoDO;
import com.yuantu.judiciary.model.dto.*;
import com.yuantu.judiciary.model.enums.AuthResultType;
import com.yuantu.judiciary.model.enums.EndpointType;
import com.yuantu.judiciary.model.enums.QueryType;
import com.yuantu.judiciary.model.enums.SearchType;
import com.yuantu.judiciary.model.form.QueryInfoForm;
import com.yuantu.judiciary.model.vo.EntListVO;
import com.yuantu.judiciary.model.vo.JudicialCaseNumVO;
import com.yuantu.judiciary.model.vo.PageVO;
import com.yuantu.judiciary.service.IApiExternalService;
import com.yuantu.judiciary.service.ICheckEnterpriseService;
import com.yuantu.judiciary.service.ICheckResultService;
import com.yuantu.judiciary.service.IOpenApiService;
import com.yuantu.judiciary.utils.AesUtil;
import com.yuantu.judiciary.utils.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;


@Service
@Slf4j
@RequiredArgsConstructor
public class ApiExternalServiceImpl implements IApiExternalService {


    private final IQueryRecordDao queryRecordDao;

    private final ICheckResultService checkResultService;

    private final IOpenApiService openService;
    private static final Gson GSON = new Gson();

    private static final String idReg = "^\\d{17}(\\d|x|X)$";

    private static final String keyOne = "xucsg&aEjI2cxchg";


    private final ISearchRecordInfoDao searchRecordInfoDao;

    private final ICheckEnterpriseService checkEnterpriseService;

    private final IExternalRequestRecordDao externalRequestRecordDao;

    @Override
    public String queryCaseNum(QueryInfoForm data) {

        String name = data.getName();
        String idNumber = data.getIdNumber();
        if (name == null) {
            throw new RuntimeException("被查询人姓名/企业名称");
        }
        if (data.getSearchType() == 1) {
            if (idNumber == null) {
                throw new RuntimeException("身份证号不能为空");
            }
            if (!idNumber.matches(idReg)) {
                throw new RuntimeException("身份证号格式错误");
            }
        }
        Timestamp now = new Timestamp(System.currentTimeMillis());
        String content = JSON.toJSONString(data);
        QueryRecordDO record;
        if (StringUtil.isNotBlank(idNumber)) {
            record = queryRecordDao.findInfoByContentAndTypeAndCreatorId(content, SearchType.PERSON, -1L);
        } else {
            record = queryRecordDao.findInfoByContentAndTypeAndCreatorId(content, SearchType.ENTERPRISE, -1L);
        }
        if (record == null) {
            record = new QueryRecordDO();
            record.setContent(content);
            if (StringUtil.isNotBlank(idNumber)) {
                record.setType(SearchType.PERSON);
            } else {
                record.setType(SearchType.ENTERPRISE);
            }
            record.setAuthorizedResult(AuthResultType.AUTHORIZED);
            record.setAuthorizedTime(now);
            record.setCreatorId(-1L);
            record.setCreateTime(now);

            queryRecordDao.save(record);
        }
        SearchRecordContentDTO searchRecord = JSON.parseObject(record.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(-1L, record, searchRecord);
        String jsonData = checkResultService.getJsonDataProd(-1L, StringUtil.isNotBlank(idNumber) ? QueryType.PER_JUDICIAL :
                QueryType.ENT_JUDICIAL, searchRecord, entity);
        JudicialCaseNumVO judicialCaseNum = new JudicialCaseNumVO();
        if (StringUtil.isNotBlank(jsonData)) {
            ResJudicialDataProdDTO resJudicialData = JSON.parseArray(jsonData, ResJudicialDataProdDTO.class).get(0);
            ResJudicialDataDTO.Detail detail = resJudicialData.getDetail();
            judicialCaseNum.setCivilCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCivil).map(ResJudicialDataDTO.Detail.Civil::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setCriminalCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCriminal).map(ResJudicialDataDTO.Detail.Criminal::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setAdministrativeCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getAdministrative).map(ResJudicialDataDTO.Detail.Administrative::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setPreservationCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getPreservation).map(ResJudicialDataDTO.Detail.Preservation::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setImplementCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getImplement).map(ResJudicialDataDTO.Detail.Implement::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setBankruptCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getBankrupt).map(ResJudicialDataDTO.Detail.Bankrupt::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setJurisdictionCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getJurisdict).map(ResJudicialDataDTO.Detail.Jurisdict::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setCompensateCasesNum(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCompensate).map(ResJudicialDataDTO.Detail.Compensate::getCases).orElse(new ArrayList<>()).size());
            judicialCaseNum.setDishonestInfoCasesNum(Optional.ofNullable(resJudicialData.getSx()).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>()).size());
            judicialCaseNum.setLimitHighCasesNum(Optional.ofNullable(resJudicialData.getXg()).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>()).size());
        } else {
            judicialCaseNum.setCivilCasesNum(0);
            judicialCaseNum.setCriminalCasesNum(0);
            judicialCaseNum.setAdministrativeCasesNum(0);
            judicialCaseNum.setPreservationCasesNum(0);
            judicialCaseNum.setImplementCasesNum(0);
            judicialCaseNum.setBankruptCasesNum(0);
            judicialCaseNum.setJurisdictionCasesNum(0);
            judicialCaseNum.setCompensateCasesNum(0);
            judicialCaseNum.setDishonestInfoCasesNum(0);
            judicialCaseNum.setLimitHighCasesNum(0);
        }
        String enCodeStr = "";
        try {
            enCodeStr = AesUtil.aesEncrypt(GSON.toJson(judicialCaseNum), keyOne);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return enCodeStr;
    }

    @Override
    public String getEnterpriseList(HttpServletRequest request, String sign) {

        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        Pageable pageable = PageRequest.of(0, 20);
        PageVO<EntListVO> enterPageInfos = checkEnterpriseService.getEnterpriseList(rawStr, pageable);
        List<EntListVO> enterList = enterPageInfos.getData();
        if (!enterList.isEmpty()) {
            String jsonData = GSON.toJson(enterList);
            String enCodeStr = "";
            try {
                enCodeStr = AesUtil.aesEncrypt(jsonData, requestKey);
            } catch (Exception e) {
                log.error("加密失败", e);
                return "加密失败";
            }
            Date now = new Date();
            SearchRecordInfoDO searchRecordInfo = new SearchRecordInfoDO();
            searchRecordInfo.setSearchContent(rawStr);
            searchRecordInfo.setSearchType("ENT_NAME");
            searchRecordInfo.setSearchEncrypt(requestKey);
            searchRecordInfo.setSearchTime(now);
            searchRecordInfoDao.save(searchRecordInfo);
            return enCodeStr;
        }
        return null;
    }


    @Override
    public String queryCompanyTaxBreakInfo(HttpServletRequest request, String sign) {

        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        CompanyTaxBreakQueryDTO companyTaxBreakQuery;
        try {
            companyTaxBreakQuery = JSON.parseObject(rawStr, CompanyTaxBreakQueryDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "企业税收违法查询对象转换失败";
        }
        if (StringUtil.isEmpty(companyTaxBreakQuery.getCreditCode())) {
            return "企业信用代码不能为空";
        }
        if (StringUtil.isEmpty(companyTaxBreakQuery.getName())) {
            return "企业名称不能为空";
        }
        if (ObjectUtils.isEmpty(companyTaxBreakQuery.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != companyTaxBreakQuery.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(companyTaxBreakQuery.getName());
        recordContent.setCreditCode(companyTaxBreakQuery.getCreditCode());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_TAX_BREAK, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_TAX_BREAK);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_TAX_BREAK);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.ENT_TAX_BREAK, requestKey);
    }


    @Override
    public String queryCompanyAdminPunishInfo(HttpServletRequest request, String sign) {
        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        CompanyAdminPunishQueryDTO companyAdminPunishQuery;
        try {
            companyAdminPunishQuery = JSON.parseObject(rawStr, CompanyAdminPunishQueryDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "企业行政处罚查询对象转换失败";
        }
        if (StringUtil.isEmpty(companyAdminPunishQuery.getName())) {
            return "企业名称不能为空";
        }
        if (ObjectUtils.isEmpty(companyAdminPunishQuery.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != companyAdminPunishQuery.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(companyAdminPunishQuery.getName());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_ADMINISTRATION, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_ADMINISTRATION);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_ADMINISTRATION);
        }
        if (StringUtil.isEmpty(jsonDataInfo) && !"{}".equals(jsonDataInfo)) {
            CaseAdministrationPunishDTO caseAdministrationPunish = JSON.parseObject(jsonDataInfo, CaseAdministrationPunishDTO.class);
            List<CaseAdministrationPunishDetailDTO> items = caseAdministrationPunish.getItems();
            jsonDataInfo = JSON.toJSONString(items);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.ENT_ADMINISTRATION, requestKey);
    }

    @Override
    public String queryCompanyJudicialCaseInfo(HttpServletRequest request, String sign) {
        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        CompanyAdminPunishQueryDTO companyAdminPunishQuery;
        try {
            companyAdminPunishQuery = JSON.parseObject(rawStr, CompanyAdminPunishQueryDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "企业涉诉查询对象转换失败";
        }
        if (StringUtil.isEmpty(companyAdminPunishQuery.getName())) {
            return "企业名称不能为空";
        }
        if (ObjectUtils.isEmpty(companyAdminPunishQuery.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != companyAdminPunishQuery.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(companyAdminPunishQuery.getName());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResJudicialDataDTO.Detail detail = resJudicialDataProd.getDetail();
            JudicialCaseDTO judicialCaseInfo = new JudicialCaseDTO();
            judicialCaseInfo.setJurisdictionCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getJurisdict).map(ResJudicialDataDTO.Detail.Jurisdict::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setPreservationCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getPreservation).map(ResJudicialDataDTO.Detail.Preservation::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setAdministrativeCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getAdministrative).map(ResJudicialDataDTO.Detail.Administrative::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setCivilCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCivil).map(ResJudicialDataDTO.Detail.Civil::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setImplementCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getImplement).map(ResJudicialDataDTO.Detail.Implement::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setCriminalCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCriminal).map(ResJudicialDataDTO.Detail.Criminal::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setCompensateCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCompensate).map(ResJudicialDataDTO.Detail.Compensate::getCases).orElse(new ArrayList<>()));
            jsonDataInfo = JSON.toJSONString(judicialCaseInfo);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.ENT_JUDICIAL, requestKey);
    }

    @Override
    public String queryCompanyBankruptCaseInfo(HttpServletRequest request, String sign) {
        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        CompanyAdminPunishQueryDTO companyAdminPunishQuery;
        try {
            companyAdminPunishQuery = JSON.parseObject(rawStr, CompanyAdminPunishQueryDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "企业破产清算查询对象转换失败";
        }
        if (StringUtil.isEmpty(companyAdminPunishQuery.getName())) {
            return "企业名称不能为空";
        }
        if (ObjectUtils.isEmpty(companyAdminPunishQuery.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != companyAdminPunishQuery.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(companyAdminPunishQuery.getName());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResJudicialDataDTO.Detail detail = resJudicialDataProd.getDetail();
            List<CaseBankruptDTO> cases = Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getBankrupt).
                    map(ResJudicialDataDTO.Detail.Bankrupt::getCases).orElse(new ArrayList<>());
            jsonDataInfo = JSON.toJSONString(cases);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.ENT_BANKRUPT, requestKey);
    }

    @Override
    public String queryCompanyDishonestCaseInfo(HttpServletRequest request, String sign) {
        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        CompanyAdminPunishQueryDTO companyAdminPunishQuery;
        try {
            companyAdminPunishQuery = JSON.parseObject(rawStr, CompanyAdminPunishQueryDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "企业失信查询对象转换失败";
        }
        if (StringUtil.isEmpty(companyAdminPunishQuery.getName())) {
            return "企业名称不能为空";
        }
        if (ObjectUtils.isEmpty(companyAdminPunishQuery.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != companyAdminPunishQuery.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(companyAdminPunishQuery.getName());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResDishonestDataDTO sx = resJudicialDataProd.getSx();
            DishonestCaseDTO dishonestCase = new DishonestCaseDTO();
            dishonestCase.setDishonestCurrentInfos(Optional.ofNullable(sx).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>()));
            dishonestCase.setDishonestRemovedInfos(Optional.ofNullable(sx).map(ResDishonestDataDTO::getSxbzxr_removed).orElse(new ArrayList<>()));
            jsonDataInfo = JSON.toJSONString(dishonestCase);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.ENT_DISHONEST, requestKey);
    }

    @Override
    public String queryCompanyHighLimitCaseInfo(HttpServletRequest request, String sign) {

        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        CompanyAdminPunishQueryDTO companyAdminPunishQuery;
        try {
            companyAdminPunishQuery = JSON.parseObject(rawStr, CompanyAdminPunishQueryDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "企业限制高消查询对象转换失败";
        }
        if (StringUtil.isEmpty(companyAdminPunishQuery.getName())) {
            return "企业名称不能为空";
        }
        if (ObjectUtils.isEmpty(companyAdminPunishQuery.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != companyAdminPunishQuery.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(companyAdminPunishQuery.getName());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.ENTERPRISE, QueryType.ENT_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResLimitDataDTO xg = resJudicialDataProd.getXg();
            LimitHighCaseDTO limitHighCase = new LimitHighCaseDTO();
            limitHighCase.setLimitHighCurrentInfos(Optional.ofNullable(xg).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>()));
            limitHighCase.setLimitHighRemovedInfos(Optional.ofNullable(xg).map(ResLimitDataDTO::getXgbzxr_removed).orElse(new ArrayList<>()));
            jsonDataInfo = JSON.toJSONString(limitHighCase);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.ENT_LIMIT, requestKey);
    }

    @Override
    public String queryPersonJudicialCaseInfo(HttpServletRequest request, String sign) {

        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        PersonBadRecordDTO personBadRecord;
        try {
            personBadRecord = JSON.parseObject(rawStr, PersonBadRecordDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "个人涉诉查询对象转换失败";
        }
        if (StringUtil.isEmpty(personBadRecord.getName())) {
            return "姓名不能为空";
        }
        if (StringUtil.isEmpty(personBadRecord.getId())) {
            return "身份证号不能为空";
        }
        if (ObjectUtils.isEmpty(personBadRecord.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != personBadRecord.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(personBadRecord.getName());
        recordContent.setIdNumber(personBadRecord.getId());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResJudicialDataDTO.Detail detail = resJudicialDataProd.getDetail();
            JudicialCaseDTO judicialCaseInfo = new JudicialCaseDTO();
            judicialCaseInfo.setJurisdictionCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getJurisdict).map(ResJudicialDataDTO.Detail.Jurisdict::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setPreservationCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getPreservation).map(ResJudicialDataDTO.Detail.Preservation::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setAdministrativeCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getAdministrative).map(ResJudicialDataDTO.Detail.Administrative::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setCivilCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCivil).map(ResJudicialDataDTO.Detail.Civil::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setImplementCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getImplement).map(ResJudicialDataDTO.Detail.Implement::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setCriminalCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCriminal).map(ResJudicialDataDTO.Detail.Criminal::getCases).orElse(new ArrayList<>()));
            judicialCaseInfo.setCompensateCases(Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getCompensate).map(ResJudicialDataDTO.Detail.Compensate::getCases).orElse(new ArrayList<>()));
            jsonDataInfo = JSON.toJSONString(judicialCaseInfo);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.PER_JUDICIAL, requestKey);
    }

    @Override
    public String queryPersonBankruptCaseInfo(HttpServletRequest request, String sign) {

        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        PersonBadRecordDTO personBadRecord;
        try {
            personBadRecord = JSON.parseObject(rawStr, PersonBadRecordDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "个人破产清算查询对象转换失败";
        }
        if (StringUtil.isEmpty(personBadRecord.getName())) {
            return "姓名不能为空";
        }
        if (StringUtil.isEmpty(personBadRecord.getId())) {
            return "身份证号不能为空";
        }
        if (ObjectUtils.isEmpty(personBadRecord.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != personBadRecord.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(personBadRecord.getName());
        recordContent.setIdNumber(personBadRecord.getId());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResJudicialDataDTO.Detail detail = resJudicialDataProd.getDetail();
            List<CaseBankruptDTO> cases = Optional.ofNullable(detail).map(ResJudicialDataDTO.Detail::getBankrupt).
                    map(ResJudicialDataDTO.Detail.Bankrupt::getCases).orElse(new ArrayList<>());
            jsonDataInfo = JSON.toJSONString(cases);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.PER_BANKRUPT, requestKey);
    }

    @Override
    public String queryPersonDishonestCaseInfo(HttpServletRequest request, String sign) {

        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        PersonBadRecordDTO personBadRecord;
        try {
            personBadRecord = JSON.parseObject(rawStr, PersonBadRecordDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "个人失信查询对象转换失败";
        }
        if (StringUtil.isEmpty(personBadRecord.getName())) {
            return "姓名不能为空";
        }
        if (StringUtil.isEmpty(personBadRecord.getId())) {
            return "身份证号不能为空";
        }
        if (ObjectUtils.isEmpty(personBadRecord.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != personBadRecord.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(personBadRecord.getName());
        recordContent.setIdNumber(personBadRecord.getId());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResDishonestDataDTO sx = resJudicialDataProd.getSx();
            DishonestCaseDTO dishonestCase = new DishonestCaseDTO();
            dishonestCase.setDishonestCurrentInfos(Optional.ofNullable(sx).map(ResDishonestDataDTO::getSxbzxr_current).orElse(new ArrayList<>()));
            dishonestCase.setDishonestRemovedInfos(Optional.ofNullable(sx).map(ResDishonestDataDTO::getSxbzxr_removed).orElse(new ArrayList<>()));
            jsonDataInfo = JSON.toJSONString(dishonestCase);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.PER_DISHONEST, requestKey);
    }

    @Override
    public String queryPersonHighLimitCaseInfo(HttpServletRequest request, String sign) {

        String ticket = request.getHeader("ticket");
        ExternalQuestRecordDO externalQuestRecord = externalRequestRecordDao.findInfoByRequestTicket(ticket);
        String requestKey = externalQuestRecord.getRequestKey();
        String rawStr = null;
        try {
            rawStr = AesUtil.aesDecrypt(sign, requestKey);
        } catch (Exception e) {
            log.error("解密失败", e);
            return "解密失败";
        }
        PersonBadRecordDTO personBadRecord;
        try {
            personBadRecord = JSON.parseObject(rawStr, PersonBadRecordDTO.class);
        } catch (Exception e) {
            log.error("json转换失败", e);
            return "个人限制高消查询对象转换失败";
        }
        if (StringUtil.isEmpty(personBadRecord.getName())) {
            return "姓名不能为空";
        }
        if (StringUtil.isEmpty(personBadRecord.getId())) {
            return "身份证号不能为空";
        }
        if (ObjectUtils.isEmpty(personBadRecord.getAuthorize())) {
            return "授权标识不能为空";
        }
        if (1 != personBadRecord.getAuthorize()) {
            return "查询未授权";
        }
        SearchRecordContentDTO recordContent = new SearchRecordContentDTO();
        recordContent.setName(personBadRecord.getName());
        recordContent.setIdNumber(personBadRecord.getId());
        String queryContent = JSON.toJSONString(recordContent);
        int count = searchRecordInfoDao.countBySearchContentAndSearchEncrypt(rawStr, requestKey);
        String jsonDataInfo;
        if (count > 0) {
            Random random = new Random();
            int i = Math.abs(random.nextInt()) % 3;
            if (i == 0) {
                jsonDataInfo = updateJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL, recordContent);
            } else {
                jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
            }
        } else {
            jsonDataInfo = getJsonDataInfo(queryContent, externalQuestRecord.getRequestId(), SearchType.PERSON, QueryType.PER_JUDICIAL);
        }
        if (!StringUtil.isEmpty(jsonDataInfo)) {
            ResJudicialDataProdDTO resJudicialDataProd = JSON.parseArray(jsonDataInfo, ResJudicialDataProdDTO.class).get(0);
            ResLimitDataDTO xg = resJudicialDataProd.getXg();
            LimitHighCaseDTO limitHighCase = new LimitHighCaseDTO();
            limitHighCase.setLimitHighCurrentInfos(Optional.ofNullable(xg).map(ResLimitDataDTO::getXgbzxr_current).orElse(new ArrayList<>()));
            limitHighCase.setLimitHighRemovedInfos(Optional.ofNullable(xg).map(ResLimitDataDTO::getXgbzxr_removed).orElse(new ArrayList<>()));
            jsonDataInfo = JSON.toJSONString(limitHighCase);
        }
        return encryptJsonInfo(jsonDataInfo, rawStr, QueryType.PER_LIMIT, requestKey);
    }

    private String encryptJsonInfo(String jsonDataInfo, String rawStr, QueryType queryType, String requestKey) {
        try {
            String encrypt = AesUtil.aesEncrypt(jsonDataInfo, requestKey);
            Date now = new Date();
            SearchRecordInfoDO searchRecordInfo = new SearchRecordInfoDO();
            searchRecordInfo.setSearchContent(rawStr);
            searchRecordInfo.setSearchType(queryType.name());
            searchRecordInfo.setSearchEncrypt(requestKey);
            searchRecordInfo.setSearchTime(now);
            searchRecordInfoDao.save(searchRecordInfo);
            return encrypt;
        } catch (Exception e) {
            log.error("加密失败", e);
        }
        return null;
    }

    private String getJsonDataInfo(String queryContent, Long creatorId, SearchType searchType, QueryType queryType) {
        QueryRecordDO record = queryRecordDao.findInfoByContentAndTypeAndCreatorId(queryContent, searchType, creatorId);
        if (record == null) {
            record = new QueryRecordDO();
            Timestamp now = new Timestamp(System.currentTimeMillis());
            record.setContent(queryContent);
            record.setType(searchType);
            record.setAuthorizedResult(AuthResultType.AUTHORIZED);
            record.setAuthorizedTime(now);
            record.setCreatorId(creatorId);
            record.setCreateTime(now);
            queryRecordDao.save(record);
        }
        SearchRecordContentDTO searchRecord = JSON.parseObject(record.getContent(), SearchRecordContentDTO.class);
        QueryEntityDO entity = checkResultService.getQueryEntity(creatorId, record, searchRecord);
        return checkResultService.getJsonDataProd(creatorId, queryType, searchRecord, entity);
    }

    private String updateJsonDataInfo(String queryContent, Long requestId, SearchType searchType, QueryType queryType,
                                      SearchRecordContentDTO searchRecordContent) {
        QueryRecordDO record = queryRecordDao.findInfoByContentAndTypeAndCreatorId(queryContent, searchType, requestId);
        return checkResultService.updateJsonDataProd(requestId, queryType, searchRecordContent, record.getEntityId());
    }


}
